package org.victoria.common.controller;


import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.victoria.common.exception.PrivilegeException;
import org.victoria.common.exception.UpdateFailureException;
import org.victoria.common.utils.FrontUtils;
import org.victoria.common.utils.ResponseUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 2015-1-12.
 */
@Controller
public class BaseController {

    private Logger logger = Logger.getLogger(BaseController.class);

    @ExceptionHandler(Exception.class)
    public String exceptionHandler(Exception ex, HttpServletRequest request, HttpServletResponse response){
        logger.error(ex.getClass().getName()+"--->"+ex.getMessage());
        ex.printStackTrace();
        boolean isAjax = request.getHeader("Accept").startsWith("application/json");
        if (ex instanceof PrivilegeException){
            if (isAjax){
                JSONObject object = ResponseUtil.getJsonObject();
                object.put("code", 401);
                object.put("message", "拒绝操作");
                ResponseUtil.renderJson(response, object.toJSONString());
            }else {
                return "error/pri_error";
            }
        }else if (ex instanceof UpdateFailureException){
            if (isAjax){
                JSONObject object = ResponseUtil.getJsonObject();
                object.put("code", 500);
                ResponseUtil.renderJson(response, object.toJSONString());
            }else {
                return "error/update_error";
            }
        } else if (ex instanceof UnauthorizedException){
            if (isAjax){
                JSONObject object = ResponseUtil.getJsonObject();
                object.put("code", 401);
                ResponseUtil.renderJson(response, object.toJSONString());
            }else {
                return FrontUtils.REDIRECT_TO_LOGIN;
            }
        } else if (ex instanceof UnauthenticatedException){
            if (isAjax){
                JSONObject object = ResponseUtil.getJsonObject();
                object.put("code", 401);
                ResponseUtil.renderJson(response, object.toJSONString());
            }else {
                return FrontUtils.REDIRECT_TO_LOGIN;
            }
        }else{
            if (isAjax){
                JSONObject object = ResponseUtil.getJsonObject();
                object.put("code", 500);
                ResponseUtil.renderJson(response, object.toJSONString());
            }else {
                return "error/500";
            }
        }
        return null;
    }


}
